
import EventList from "../event/EventList";
import GlobalEvent from "../event/GlobalEvent";

export default class GameTimer extends EventList {

    private interval: number = 1;


    private intervalID = 0;

    private isPlaying: boolean = false

    constructor() {
        super();
        GlobalEvent.instance().addEventListener(GlobalEvent.EVENT_HIDE,this.eventHide,this)
        GlobalEvent.instance().addEventListener(GlobalEvent.EVENT_SHOW,this.eventShow,this)
    }

    eventShow(){
        if (this.isPlaying) {
            cc.log("游戏进入前台");
            this.resume();
        }
    }

    eventHide(){
        if (this.isPlaying) {
            cc.log("游戏进入后台");
            this.pause();
        }
    }
    /**
     * 
     * @param interval 
     */
    start(interval: number) {
        this.isPlaying = true;
        this.interval = interval;
        this.pause();
        this.resume();
    }

    stop() {
        this.pause();
        this.isPlaying = false;
    }

    pause() {
        if (this.intervalID > 0) {
            // cc.log("onDestroy clearInterval  this.intervalID ", this.intervalID);
            clearInterval(this.intervalID);
            this.intervalID = 0;
        }
    }

    resume() {
        if (this.intervalID == 0) {
            this.intervalID = setInterval(() => {
                // cc.log(' GameTimer resume  this.interval ',this.interval)
                this.publish(this.interval);
            }, this.interval * 1000);
        }

    }

}
